package com.example.fileio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button btn = (Button)findViewById(R.id.btn);
		
		btn.setOnClickListener(new OnClickListener(){

			EditText text = (EditText)findViewById(R.id.text);
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				save(text.getText().toString());
			}
			
		});
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void save(String s){
		FileOutputStream fos = null;
		try {
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				String path = Environment.getExternalStorageDirectory().getPath() + "/fileIo/xxx/aaa/ddd/files";
				File dir = new File(path);
				dir.mkdirs();
				fos = new FileOutputStream(new File(dir,"a.txt"),true);
				Toast.makeText(this, s.getBytes() + "------------", Toast.LENGTH_LONG).show();
				fos.write(s.getBytes());
				fos.flush();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
